import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
// import ReportFormMachineProductionStatistics from '@main/entities/service/admin/reportForm/report-form-period-status-monitoring.entity';
import {
  Repository,
  // IsNull, Between, In
} from 'typeorm';
// import { SysOperationLogService } from '../../system/operationLog/operationLog.service';
import BaseMachine from '@main/entities/service/admin/base/base-machine.entity';
// import WipOrderReport from '@main/entities/service/admin/wip/wip-order-report.entity';

@Injectable()
export class ReportFormMachineProductionStatisticsService {
  constructor(
    @InjectRepository(BaseMachine)
    private machineRepository: Repository<BaseMachine> // @InjectRepository(WipOrderReport) // private orderReportRepository: Repository<WipOrderReport>
  ) {}

  /**
   * 罗列所有配置
   */
  async list(data) {
    const { entity = {} } = data;

    const { machineCodeList, dateStartTime, dateEndTime } = entity;

    const machineCodes = machineCodeList.length
      ? `IN ('${machineCodeList.join("','")}')`
      : 'IS NOT NULL';

    const sql = `
      SELECT
    Date(DATETIME(report_time / 1000, 'unixepoch')) AS date,
    d.machine_code AS machineCode,
    d.machine_name AS machineName,
    SUM(CASE
            WHEN a.report_finish_status = 1 THEN
                CASE
                    WHEN a.report_status = 1 THEN a.report_confirm_num
                    ELSE a.report_num
                END
            ELSE 0
        END) AS outputNum
FROM
    base_machine d
LEFT JOIN
    wip_order_report a ON d.machine_code = a.machine_code
    AND Date(DATETIME(a.report_time / 1000, 'unixepoch')) BETWEEN '${dateStartTime}' AND '${dateEndTime}'
WHERE
    d.machine_code ${machineCodes}
GROUP BY
    d.machine_code,
    Date(DATETIME(a.report_time / 1000, 'unixepoch'))
ORDER BY
    Date(DATETIME(a.report_time / 1000, 'unixepoch'));`;

    const result = await this.machineRepository.query(sql);

    const resultMap = new Map<string, any>();

    // 创建日期范围内的所有日期
    const currentDate = new Date(dateStartTime);
    const end = new Date(dateEndTime);

    while (currentDate <= end) {
      const dateStr = currentDate.toISOString().split('T')[0]; // 格式化为 YYYY-MM-DD
      resultMap.set(dateStr, { date: dateStr, data: [] });
      currentDate.setDate(currentDate.getDate() + 1);
    }

    // 收集所有的设备信息
    const machineMap = new Map<string, string>(); // 机器代码与机器名称的映射
    result.forEach((row) => {
      if (row.machineCode && row.machineName) {
        machineMap.set(row.machineCode, row.machineName);
      }
    });

    // 初始化每个日期的设备信息，统计条数为 0
    const machineList = Array.from(machineMap.keys());
    machineList.forEach((machineCode) => {
      const machineName = machineMap.get(machineCode) || ''; // 获取机器名称
      resultMap.forEach((dateEntry) => {
        dateEntry.data.push({
          machineCode,
          machineName,
          outputNum: 0, // 初始化计数为 0
        });
      });
    });

    // 遍历数据并填充到对应的日期对象中
    result.forEach((row) => {
      const { date, machineCode, outputNum } = row;

      const dateEntry = resultMap.get(date);
      if (dateEntry) {
        // 查找对应的设备条目
        const machineEntry = dateEntry.data.find((m) => m.machineCode === machineCode);

        if (machineEntry) {
          // 更新计数
          machineEntry.outputNum = outputNum || 0;
        }
      }
    });

    // 将结果转换为数组
    return Array.from(resultMap.values());

    // return [];
  }
}
